package com.woniu.user.controller;


import com.woniu.common.key.PayKey;
import com.woniu.common.pojo.dto.user.PayDto;
import com.woniu.common.result.Result;
import com.woniu.common.result.ResultCode;
import com.woniu.common.util.BCrypt;
import com.woniu.user.entity.PayOrder;
import com.woniu.user.service.IPayOrderService;
import com.woniu.user.service.IUserInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 贾玉亮
 * @since 2023-01-05
 */
@RestController
@RequestMapping("/user/pay-order")
public class PayOrderController {
    @Resource
    private IPayOrderService payOrderServiceImpl;
    @Resource
    private IUserInfoService userInfoServiceImpl;
    @PostMapping("/pay")
    public Result pay(@RequestBody PayDto payDto){
        //1.判断是否是自动支付 是的话省略判断支付密码流程
        if(!PayKey.PAY_AUTO_REPAY.equals(payDto.getPayPurposes())){
            //2 .判断支付密码是否正确
            String payPassword = userInfoServiceImpl.getPayPasswordByUserId(payDto.getFkUserId());
            if (!BCrypt.matches(payDto.getPayPassword(),payPassword)){
                return Result.error(ResultCode.USER_PAY_PASSWORD_ERROR.getCode(),ResultCode.USER_PAY_PASSWORD_ERROR.getMessage());
            }
        }

        String accountType = payDto.getAccountType();
        int flag = 2;
        if (accountType.equals("0")){
            flag=payOrderServiceImpl.payForBalance(payDto);
        }else if (accountType.equals("1")){
            flag=payOrderServiceImpl.payForBank(payDto);
        }
        if (flag == 1){
            //支付成功
            return Result.ok();
        }else if (flag == 0){
            //余额不足
            return Result.error(ResultCode.USER_PAY_BALANCE_DEFICIENCY.getCode(),ResultCode.USER_PAY_BALANCE_DEFICIENCY.getMessage());
        }else {
            //支付失败
            return Result.error(ResultCode.USER_PAY_EXCEPTION.getCode(),ResultCode.USER_PAY_EXCEPTION.getMessage());
        }
    }
}

